/**
 * @Author: wanqian
 * @Date: 2021/1/30 10:16
 */
public class Queen8 {

    public static final int MAX = 8;
    public static int[] arr = new int[MAX];
    public static int result_num = 0;
    public static int judge_num = 0;

    public static void main(String[] args) {
        check(0);
        System.out.println(String.format("共有%d个解", result_num));
        System.out.println(String.format("共判断%d次", judge_num));
    }

    /**
     * 尝试在第n行摆放第n个皇后(从0开始)
     *
     * @param n
     */
    public static void check(int n) {
        if (n == MAX) {
            //打印结果
            printArr();
            result_num++;
            return;
        } else {
            for (int i = 0; i < MAX; i++) {
                arr[n] = i;
                if (judge(n)) {
                    check(n + 1);
                }
            }
        }
    }

    /**
     * 判断当前皇后的摆放与之前所有已拜访的皇后是否冲突
     *
     * @param n
     * @return
     */
    public static boolean judge(int n) {
        judge_num++;
        for (int i = 0; i < n; i++) {
            if (arr[i] == arr[n] || Math.abs(n - i) == Math.abs(arr[i] - arr[n])) {
                return false;
            }
        }
        return true;
    }

    public static void printArr() {
        for (int i : arr) {
            System.out.printf(i + "\t");
        }
        System.out.println();
    }
}
